package com.shiplanet.dao.impl;

import java.io.File;

import org.springframework.stereotype.Repository;

import com.shiplanet.dao.PhotoDAO;
import com.shiplanet.entity.Photo;
import com.shiplanet.util.Constants;
import com.shiplanet.util.ImageProcessor;

@Repository("photoDAO")
public class PhotoDAOImpl extends BaseDAOImpl<Photo> implements PhotoDAO {
	public String createPhotoFile(File photoFile, String date, String uuid, char dimension,
			String realRootPath) throws Exception {
		String fileName = null;

		String basePath = Constants.IMAGE_BASE_DIR;

		String imagePath = basePath + '/' + date + '/';

		String realImagePath = realRootPath + basePath + '/' + date + '/';

		ImageProcessor processor = new ImageProcessor(photoFile);

		// create the folder for images if not existed
		File folder = new File(realImagePath);
		if (!folder.exists())
			folder.mkdirs();

		fileName = uuid + "_" + dimension + ".jpg";
		
		switch (dimension) {
		case 'L':
			// save large image
			String iconFilePath = realRootPath + basePath + '/'
					+ Constants.IMAGE_ICON_FILENAME;

			// large image needs to be water marked
			processor
					.zoomOut(Constants.IMAGE_L_WIDTH, Constants.IMAGE_L_HEIGHT)
					.imageWaterMark(iconFilePath)
					.saveImageAs(realImagePath + fileName);
			break;
		case 'M':
			// save median image
			processor
					.zoomOut(Constants.IMAGE_M_WIDTH, Constants.IMAGE_M_HEIGHT)
					.saveImageAs(realImagePath + fileName);
			break;
		case 'S':
			// save small image
			processor
					.zoomOut(Constants.IMAGE_S_WIDTH, Constants.IMAGE_S_HEIGHT)
					.saveImageAs(realImagePath + fileName);
			break;
		default:
			break;
		}

		// set URL for database
		return imagePath + fileName;
	}

	public void deletePhotoFile(String fileName) {
		File file = new File(fileName);
		file.delete();
	}
}
